import { useKeyPress } from "ahooks";
import {
  copySelectedComponent,
  pasteCopiedComponent,
  removeSelectedComponent,
  selectNextComponent,
  selectPrevComponent,
} from "../store/componentsReducer";
import { useDispatch } from "react-redux";
import { ActionCreators as undoActionCreators } from "redux-undo";

function isActiveElementValid() {
  const activeElem = document.activeElement;

  //  这是没有加dnd-kit 的时候，是正常使用的
  // if (activeElem === document.body) return true; // 光标没有focus 到input

  // 增加了 dnd-kit 以后
  if (activeElem === document.body) return true; // 光标没有focus 到input
  if (activeElem?.matches('div[role="button"]')) return true;
  return false;
}

function useBindCanvasKeyPress() {
  const dispatch = useDispatch();
  // 删除组件
  useKeyPress(["Backspace", "delete"], () => {
    if (!isActiveElementValid()) return;
    dispatch(removeSelectedComponent());
  });
  //复制
  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementValid()) return;
    dispatch(copySelectedComponent());
  });

  // 粘贴
  useKeyPress(["ctrl.v", "meta.v"], () => {
    if (!isActiveElementValid()) return;
    dispatch(pasteCopiedComponent());
  });

  // 选中上一个
  useKeyPress("uparrow", () => {
    if (!isActiveElementValid()) return;
    dispatch(selectPrevComponent());
  });
  //选中下一个
  useKeyPress("downarrow", () => {
    if (!isActiveElementValid()) return;
    dispatch(selectNextComponent());
  });

  //撤销
  useKeyPress(
    ["ctrl.z", "meta.z"],
    () => {
      if (!isActiveElementValid) return;
      dispatch(undoActionCreators.undo());
    },
    {
      exactMatch: true, // 严格模式，精准匹配到
    }
  );

  // 重做

  useKeyPress(["ctrl.shift.z", "meta.shift.z"], () => {
    if (!isActiveElementValid) return;
    dispatch(undoActionCreators.redo());
  });
}

export default useBindCanvasKeyPress;
